/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.connector.base.message.impl;

import com.je.connector.base.connection.Connection;
import com.je.connector.base.message.MessageHandler;
import com.je.connector.base.message.PacketReceiver;
import com.je.connector.base.message.model.BaseMessage;
import com.je.connector.base.protocol.Command;
import com.je.connector.base.protocol.Packet;
import com.je.connector.base.utils.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;

/**
 * 消息分发器
 *
 * @ProjectName: instant-message
 * @Package: com.connector.base.message
 * @ClassName: MessageDispatcher
 * @Description: 定义消息分发器
 * @Author: LIULJ
 * @Version: 1.0
 * <p>Copyright: Copyright (c) 2018</p>
 */
@Slf4j
public class MessageDispatcher implements PacketReceiver {

    private final Map<Byte, MessageHandler> handlers = new HashMap<>();

    /**
     * 进行注册
     *
     * @param command
     * @param handler
     */
    public void register(Command command, MessageHandler handler) {
        handlers.put(command.cmd, handler);
    }

    public void register(Command command, Supplier<MessageHandler> handlerSupplier, boolean enabled) {
        if (enabled && !handlers.containsKey(command.cmd)) {
            register(command, handlerSupplier.get());
        }
    }

    public void register(Command command, Supplier<MessageHandler> handlerSupplier) {
        this.register(command, handlerSupplier, true);
    }

    public MessageHandler unRegister(Command command) {
        return handlers.remove(command.cmd);
    }

    @Override
    public void onReceive(Packet packet, Connection connection) {
        MessageHandler handler = handlers.get(packet.getCmd());
        if (handler != null) {
            try {
                handler.handle(packet, connection);
            } catch (Throwable throwable) {
                log.error("dispatch message ex, packet={}, connect={}, body={}"
                        , packet, connection, Arrays.toString(packet.getBody()), throwable);
                BaseMessage.buildErrorResponse(connection).setErrorCode(ErrorCode.DISPATCH_ERROR).buildResult("Dispather Error", "分发消息失败！").close();
            }
        } else {
            log.error("dispatch message failure, cmd={} unsupported", packet.getCmd());
        }
    }
}
